package com.li.onjava8.concurrent.cf.exception;

import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream;

/**
 * CompletableFutures和并行Streams都不支持包含已检查异常的操作。相反，你必须在调用操作时处理检查到的异常，这会产生不太优雅的代码
 * @author li
 * @date 2023/11/1 10:33
 */
public class ThrowsChecked {
    class Checked extends Exception {}

    static ThrowsChecked nochecked(ThrowsChecked tc) {
        return tc;
    }

    static ThrowsChecked withchecked(ThrowsChecked tc) throws Checked {
        return tc;
    }

    //如果你尝试像对 nochecked() 一样对 withchecked() 使用方法引用，则编译器会抱怨。相反，你必须写出lambda表达式（或编写一个不会引发异常的包装器方法）。

    static void testStream() {
        Stream.of(new ThrowsChecked())
                .map(ThrowsChecked::nochecked)
//                .map(ThrowsChecked::withchecked)
                .map(tc -> {
                    try {
                        return withchecked(tc);
                    } catch (Checked e) {
                        throw new RuntimeException(e);
                    }
                });
    }

    static void testCompletableFuture() {
        CompletableFuture.completedFuture(new ThrowsChecked())
                .thenApply(ThrowsChecked::nochecked)
//                .thenApply(ThrowsChecked::withchecked)
                .thenApply(tc -> {
                    try {
                        return withchecked(tc);
                    } catch (Checked e) {
                        throw new RuntimeException(e);
                    }
                });
    }


}
